<!DOCTYPE html>
<html lang="zh_CN">
<head>
    <meta charset="utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>点餐</title>
    <link rel="stylesheet" href="${ctxPath}/assets/libs/layui/css/layui.css"/>
    <link rel="stylesheet" href="${ctxPath}/assets/module/admin.css">
    <!--[if lt IE 9]>
    <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
    <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
    <style>
        #dishPackageTree {
            border: 1px solid #e6e6e6;
            padding: 10px 5px;
            overflow: auto;
            height: -webkit-calc(100vh - 125px);
            height: -moz-calc(100vh - 125px);
            height: calc(100vh - 125px);
        }

        .layui-tree-entry .layui-tree-txt {
            padding: 0 5px;
            border: 1px transparent solid;
            text-decoration: none !important;
        }

        .layui-tree-entry.ew-tree-click .layui-tree-txt {
            background-color: #fff3e0;
            border: 1px #FFE6B0 solid;
        }
    </style>
</head>
<body>
<!-- 正文开始 -->
<div class="layui-fluid">
    <div class="layui-row layui-col-space15">
        <div class="layui-col-md6">
            <div class="layui-card">
                <div class="layui-card-body" style="padding: 10px;">
                    <!-- 表格工具栏 -->
                    <form class="layui-form toolbar">
                        <div class="layui-form-item">
                            <div class="layui-inline">
                                <label class="layui-form-label">名称:</label>
                                <div class="layui-input-inline">
                                    <input name="name" class="layui-input" placeholder="请输入名称"/>
                                </div>
                            </div>
                            <div class="layui-inline">&emsp;
                                <button class="layui-btn icon-btn" lay-filter="tableSearch" lay-submit>
                                    <i class="layui-icon">&#xe615;</i>搜索
                                </button>
                                <button type="reset" class="layui-btn layui-btn-primary icon-btn">
                                    <i class="layui-icon">&#xe669;</i>重置
                                </button>
                            </div>
                        </div>
                    </form>
                    <!-- 数据表格 -->
                    <table id="dataTable" lay-filter="dataTable"></table>
                </div>
            </div>
        </div>
        <div class="layui-col-md6">
            <div class="layui-card">
                <div class="layui-card-header" >
                    <p><span class="pull-left" id="carname"></span></p>
                    <p><span class="pull-right" id="allsum"></span></p>
                </div>
                <div class="layui-card-body">
                    <table id="orderTable" lay-filter="orderTable"></table>
                </div>
                <span id="getid" class="hidden"></span>
                <span id="getdata" class="hidden"></span>
            </div>
        </div>
    </div>
</div>
<!-- 表格操作列 -->
<script type="text/html" id="tableBar">
    <a class="layui-btn layui-btn-warm layui-btn-xs" perm-show="order:add" lay-event="add">加入餐车</a>
</script>

<script type="text/html" id="tableBar2">
    <a class="layui-btn layui-btn-primary layui-btn-xs" perm-show="order:edit" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" perm-show="order:delete" lay-event="delete">删除</a>
</script>

<!-- js部分 -->
<script src="${ctxPath}/assets/libs/layui/layui.js"></script>
<script src="${ctxPath}/assets/js/common.js"></script>

<script>
    layui.use(['layer', 'table', 'tableX', 'notice', 'tree', 'treeTable', 'xnUtil'], function () {
        var $ = layui.jquery;
        var layer = layui.layer;
        var table = layui.table;
        var tableX = layui.tableX;
        var admin = layui.admin;
        var form = layui.form;
        var notice = layui.notice;
        var xnUtil = layui.xnUtil;
        var tree = layui.tree;
        var laydate = layui.laydate;



        // 渲染字典下拉
        xnUtil.rendDictDropDown(null, 'kind', 'dish_kind', '请选择种类', null);

        $("#carname").text(getName()+"的购物车")

        /* 渲染表格 */
        var insTb = tableX.render({
            elem: '#dataTable',
            url: getProjectUrl() + 'dishPackage/page',
            page: true,
            cellMinWidth: 100,
            cols: [
                [
                    {field: 'kind', title: '种类', sort: true, templet: function (d) {  return xnUtil.rendDataTableDict(d.kind, 'dish_kind'); }},
                    {field: 'name', title: '名称', sort: true},
                    {field: 'price', title: '价格', sort: true},
                    {title: '操作', toolbar: '#tableBar', align: 'center'}
                ]
            ],
            done: function(res, curr, count) {


                //不显示价格为0的行
                var that = this.elem.next();
                res.data.forEach(function (item, index) {
                    if (item.price == 0) {
                        console.log(item.price);
                        var tr = that.find(".layui-table-box tbody tr[data-index='" + index + "']");
                        tr.css("display", "none");
                        tr.find(".laytable-cell-1-0-9").css("display","none");

                    }
                });
                xnUtil.tableDone(insTb, res, curr, count);
            }
        });


        var hn=getName();

        function ordersum(data){
            var box=document.getElementById('allsum')
            var sum=box.innerText
            var a=sum.substring(4);
            $.ajax({
                url : getProjectUrl() +"hallRoomJoint/setHallSum/"+data.id+"/"+a,//后台请求的数据
                dataType: 'json', //数据格式
                type : "get",//请求方式
                async : true,//是否异步请求
                success : function() {

                },
                error : function (arg1) {
                    console.log(arg1);
                }
            })
        }
        /* 渲染表格 */
        var insTb2 = tableX.render({
            elem: '#orderTable',
            url: getProjectUrl() + 'order/page',
            where:{hallname:hn,status:0},
            page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
                layout: ['limit', 'count', 'prev', 'page', 'next', 'skip'] //自定义分页布局
                ,limit:50 //每页显示的条数
            },
            toolbar: ['<p>',
                '<button lay-event="setSum" perm-show="order:setSum:{id}:{sum}" class="layui-btn layui-btn-sm icon-btn"><i class="layui-icon">&#xe654;</i>点单</button>&nbsp;',
                '</p>'].join(''),
            cellMinWidth: 80,
            cols: [
                [
                    {field: 'hallname', title: '消费包厢', sort: true,hide:true},
                    {field: 'orderId', title: '表id自增', sort: true,hide:true},
                    {field: 'name', title: '消费项目', sort: true},
                    {field: 'number', title: '份数', sort: true , width:70},
                    {field: 'unit', title: '单位', sort: true,width:70, templet: function (d) {  return xnUtil.rendDataTableDict(d.unit, 'order_unit'); }},
                    {field: 'price', title: '价格', sort: true,width:70},
                    {field: 'status', title: '是否结账', sort: true,  hide :true ,templet: function (d) {  return xnUtil.rendDataTableDict(d.status, 'pay_status'); }},
                    {title: '操作', toolbar: '#tableBar2', align: 'center'}
                ]
            ],
            done: function(res, curr, count) {
                var sum=0;
                $("#getdata").text=res.data;
                layui.each(res.data, function(index, item){
                    if(item.status==0){
                        sum=sum+item.price*item.number;
                    }

                });
                $("#allsum").text("总价：¥"+sum);
                xnUtil.tableDone(insTb, res, curr, count);
            }
        });



        /* 表格搜索 */
        form.on('submit(tableSearch)', function (data) {
            insTb.reload({where: data.field, page: {curr: 1}});
            return false;
        });

        var ids=new Array();

        /* 表格工具条点击事件 */
        table.on('tool(dataTable)', function (obj) {
            if (obj.event === 'add') {
                AddModel(obj.data);

            }
        });

        table.on('tool(orderTable)', function (obj) {
            if (obj.event === 'delete') {
            layer.confirm('确定移除餐车吗？', {
                skin: 'layui-layer-admin',
                shade: .1
            }, function () {
                admin.req(getProjectUrl() + 'order/delete', JSON.stringify([{'id': obj.data.id}]), function(res){
                    layer.msg(res.message, {icon: 1, time: 1000}, function () {
                        insTb2.reload();
                    });
                }, 'post');
            });
        }
            if (obj.event === 'edit') {
                editModel(obj.data);
            }
        });

        table.on('toolbar(orderTable)', function (obj) {

            if (obj.event === 'setSum') { // 点单
                var box=document.getElementById('allsum');
                var sum=box.innerText;
                var a=sum.substring(4);
                if(a!=0){
                    updateModel();
                    layer.confirm('确定加入购物车吗？', {
                        skin: 'layui-layer-admin',
                        shade: .1
                    }, function () {
                        var box=document.getElementById('allsum');
                        var sum=box.innerText;
                        var a=sum.substring(4);
                        for(i=0;i<ids.length;i++){

                            setSum(ids[i],a);
                            delete ids[i];

                        }

                        layer.msg('点餐成功,订单总额为:¥'+a+'</br>将在3秒后返回点餐页面');
                        setTimeout("window.location.href='/hallRoomJoint/order'", 3000 );

                    })
                }
                else {
                    layer.msg('请点餐！');
                }
                getOrderData();//传数据到bill表
            }

        });

        function updateModel(){
            $.ajax({
                url : getProjectUrl() +"hallRoomJoint/list",//后台请求的数据
                dataType: 'json', //数据格式
                type : "get",//请求方式
                async : true,//是否异步请求
                success : function(data) {   //如果请求成功，返回数据。
                    layui.each(data.data, function(index, item){
                        if(item.name==getName()){   //找到对应餐台
                            toBehindHallSum(item);  //设置该餐台的消费总额
                        }
                    });

                },
                error : function (arg1) {
                    alert("加载数据失败");
                    console.log(arg1);
                }
            })
        }

        function setSum(id,sum){
            $.ajax({
                url : getProjectUrl() +"order/setSum/"+id+"/"+sum,//后台请求的数据
                dataType: 'json', //数据格式
                type : "GET",//请求方式
                async : true,//是否异步请求
                success : function() {
                },
                error : function (arg1) {
                    console.log(arg1);
                }
            })
        }



        function toBehindHallSum(data){
            var box=document.getElementById('allsum')
            var sum=box.innerText
            var a=sum.substring(4);
            $.ajax({
                url : getProjectUrl() +"hallRoomJoint/setHallSum/"+data.id+"/"+a,//后台请求的数据
                dataType: 'json', //数据格式
                type : "get",//请求方式
                async : true,//是否异步请求
                success : function() {

                },
                error : function (arg1) {
                    console.log(arg1);
                }
            })
        }




        // 显示表单弹窗
        function AddModel(data) {
            data.id=getDtId();
            ids.push(data.id);
            // $("#getid").text(data.id);
            data.orderId=getRequest();
            data.hallname=getName();
            var layIndex = admin.open({
                title:  '添加餐品',
                url: getProjectUrl() + 'order/form',
                data: {
                    data: data
                },     // 传递数据到表单页面
                end: function () {
                    var layerData = admin.getLayerData(layIndex, 'formOk');
                    if (layerData) {  // 判断表单操作成功标识
                        insTb.reload();  // 成功刷新表格
                        insTb2.reload();
                    }
                },
                success: function (layero, dIndex) {

                    // 弹窗超出范围不出现滚动条
                    $(layero).children('.layui-layer-content').css('overflow', 'visible');
                    $(layero).find('[lay-submit]').focus();
                }
            });
            return data.id;
        }

        function editModel(data) {
            data.orderId=getRequest();
            data.hallname=getName();
            var layIndex = admin.open({
                title:  '编辑餐品',
                url: getProjectUrl() + 'order/form',
                data: {
                    data: data
                },     // 传递数据到表单页面
                end: function () {
                    var layerData = admin.getLayerData(layIndex, 'formOk');
                    if (layerData) {  // 判断表单操作成功标识
                        insTb.reload();  // 成功刷新表格
                        insTb2.reload();
                    }
                },
                success: function (layero, dIndex) {
                    // 弹窗超出范围不出现滚动条
                    $(layero).children('.layui-layer-content').css('overflow', 'visible');
                    $(layero).find('[lay-submit]').focus();
                }
            });
        }
    });



    function getRequest(){
        var url = location.search; //获取url中"?"符后的字串
        if (url.indexOf("?") != -1) { //如果？没被删掉
            var str = url.substr(1); //str去掉了？
            strs = str.split("&"); //去掉&
            var a=decodeURIComponent(strs);
            var b=a.substring(3,a.indexOf(","));
        }
        return b;//b是传过来的id
    }


    function getDtId() {
        var id=document.getElementById("getid");
        id.style.display="none";
        var d = new Date();
        var year = d.getFullYear();
        var month = d.getMonth() + 1;
        var date = d.getDate();
        var day = d.getDay();
        var hours = d.getHours();
        var minutes = d.getMinutes();
        var seconds = d.getSeconds();
        var ms = d.getMilliseconds();
        year = (year + "").substring(2);
        if (month <= 9)
            month = "0" + month;
        if (date <= 9)
            date = "0" + date;
        if (hours <= 9)
            hours = "0" + hours;
        if (minutes <= 9)
            minutes = "0" + minutes;
        if (seconds <= 9)
            seconds = "0" + seconds;
        let num = Math.ceil(Math.random()*100);
        var id = year + month + date + hours + minutes + seconds + num;
        return id;
    }


    function getName(){
        var url = location.search; //获取url中"?"符后的字串
        if (url.indexOf("?") != -1) { //如果？没被删掉
            var str = url.substr(1); //str去掉了？
            strs = str.split("&"); //去掉&
            var a=decodeURIComponent(strs);
            var c = a.substring(a.indexOf("e")+2);
            return c;
        }
    }

    function getOrderData() {
        var jsonObj = [];
        var $ = layui.$;
        $("[lay-id='orderTable'] tbody tr").each(function (i) {
            var jsonStr = "{";// json格式开始
            $(this).children('td').each(function (j) {  // 遍历 tr 的各个 td
                jsonStr += '"' + $(this).data('field') + '":' + '"' + $(this).text() + '",';
            });
            jsonStr = jsonStr.replace(/,{1}$/gi, '');// 删除最后的逗号
            jsonStr += "}";// //json格式结束
            jsonObj.push(jsonStr);
        })
        var box = document.getElementById('allsum');
        var sum1 = box.innerText;
        var sum = sum1.substring(4);//a是sum
        var id = getDtId();
        var name = "";
        var num = 0;
        layui.each(jsonObj, function (index, item) {
            var s1 = item.substring(item.indexOf(":") + 2)
            var hallname = s1.substring(0, s1.indexOf("\""))
            var s2 = item.substring(item.indexOf(",") + 1)
            var s3 = s2.substring(s2.indexOf(",") + 1)
            var s4 = s3.substring(s3.indexOf(":") + 2)
            var name1 = s4.substring(0, s4.indexOf("\""))
            var s5 = s4.substring(s4.indexOf(":") + 2)
            var number = s5.substring(0, s5.indexOf("\""))
            var s6 = s5.substring(s5.indexOf(":") + 2)
            var unit = s6.substring(0, s6.indexOf("\""))
            var s7 = s6.substring(s6.indexOf(":") + 2)
            var price = s7.substring(0, s7.indexOf("\""))
            num++
            name += num + ". " + name1 + " " + number + " " + unit + " ¥" + price + "," + " "
        });
        var hallname = getName();
        $.ajax({
            url: getProjectUrl() + "bill/setAll/" + id + "/" + name + "/" + sum + "/" + hallname,//后台请求的数据
            dataType: 'json', //数据格式
            type: "GET",//请求方式
            async: true,//是否异步请求
            success: function () {

            },
            error: function (arg1) {
                console.log(arg1);
            }
        })
    }





</script>


</body>
</html>